import sys

from PyQt5.QtCore import Qt
from PyQt5.QtSql import QSqlDatabase, QSqlQuery, QSqlTableModel, QSqlQueryModel
from PyQt5.QtWidgets import QApplication, QTableView, QDialog, QVBoxLayout, QPushButton, QWidget, QHBoxLayout, \
    QLineEdit, QLabel, QSplitter, QHeaderView, QMessageBox

'''
PyQt5 分页显示数据 SQLite数据库 案例
limit n,m
'''


class DataGrid(QWidget):
    def createTableAndInit(self):
        # 添加数据
        self.db = QSqlDatabase.addDatabase('QSQLITE')
        # 设置数据库名称
        self.db.setDatabaseName('db.db')
        # 判断是否打开
        if not self.db.open():
            print('没打开数据库')
            return False

        # 打印当前数据库中的表
        print(self.db.tables())

        # 声明数据库查询对象
        query = QSqlQuery()

        # 创建表
        if query.exec(
                "create table student (id int primary key,name varchar(30),sex varchar(30),age int,subject varchar(30))"):
            print('Table Created!')

        # 添加记录
        if query.exec("insert into student values(1,'张三','男',20,'计算机')"):
            print("succeed insert data.")
        query.exec("insert into student values(2,'张四','男',19,'警官')")
        query.exec("insert into student values(3,'张五','男',20,'法律')")
        query.exec("insert into student values(4,'张六','男',18,'机械')")
        query.exec("insert into student values(5,'王三','男',22,'物理')")
        query.exec("insert into student values(6,'张三','男',21,'化学')")
        query.exec("insert into student values(7,'张三','男',20,'生物')")
        query.exec("insert into student values(8,'张三','男',18,'历史')")
        query.exec("insert into student values(9,'张三','男',20,'英语')")
        query.exec("insert into student values(10,'张三','男',20,'英语')")
        query.exec("insert into student values(11,'张三','男',20,'机械')")
        query.exec("insert into student values(12,'张三','男',22,'计算机')")
        query.exec("insert into student values(13,'张三','男',20,'法律')")
        query.exec("insert into student values(14,'张三','男',20,'计算机')")
        query.exec("insert into student values(15,'张三','男',22,'物理')")
        query.exec("insert into student values(16,'张三','男',24,'计算机')")
        query.exec("insert into student values(17,'张三','男',23,'计算机')")
        return True

    def __init__(self):
        super().__init__()
        self.setWindowTitle('分页显示数据')
        self.resize(800, 400)
        self.createTableAndInit()

        # 当前页
        self.currentPage = 0
        # 总页数
        self.totalPage = 0
        # 总记录数
        self.totalRecrodCount = 0
        # 每页显示记录数
        self.PageRecordCount = 5

        self.initUI()

    def initUI(self):
        # 创建窗口
        self.createWindow()
        # 设置表格
        self.setTableView()

        # 信号槽连接
        self.prevButton.clicked.connect(self.onPrevButtonClick)
        self.nextButton.clicked.connect(self.onNextButtonClick)
        self.switchPageButton.clicked.connect(self.onSwitchPageButtonClick)

    def closeEvent(self, event):
        print('关闭数据库')
        # 关闭数据库
        self.db.close()

    # 创建窗口
    def createWindow(self):
        # 操作布局
        operatorLayout = QHBoxLayout()
        self.prevButton = QPushButton("前一页")
        self.nextButton = QPushButton("后一页")
        self.switchPageButton = QPushButton("GO")
        self.switchPageLineEdit = QLineEdit()
        self.switchPageLineEdit.setFixedWidth(40)

        switchPage = QLabel('转到第')
        page = QLabel('页')
        operatorLayout.addWidget(self.prevButton)
        operatorLayout.addWidget(self.nextButton)
        operatorLayout.addWidget(switchPage)
        operatorLayout.addWidget(self.switchPageLineEdit)
        operatorLayout.addWidget(page)
        operatorLayout.addWidget(self.switchPageButton)
        operatorLayout.addWidget(QSplitter())

        # 状态布局
        statusLayout = QHBoxLayout()
        self.totalPageLabel = QLabel()
        self.totalPageLabel.setFixedWidth(70)
        self.currentPageLabel = QLabel()
        self.currentPageLabel.setFixedWidth(70)

        self.totalRecordLabel = QLabel()
        self.totalRecordLabel.setFixedWidth(70)

        statusLayout.addWidget(self.totalPageLabel)
        statusLayout.addWidget(self.totalRecordLabel)
        statusLayout.addWidget(self.currentPageLabel)
        statusLayout.addWidget(QSplitter())
        operatorWidget = QWidget()
        operatorWidget.setLayout(operatorLayout)
        statusLayout.addWidget(operatorWidget)

        # 设置表格属性
        self.tableView = QTableView()
        # 表格宽度的自适应调整
        self.tableView.horizontalHeader().setStretchLastSection(True)
        self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

        # 创建界面
        mainLayout = QVBoxLayout(self)
        # mainLayout.addLayout(operatorLayout)
        mainLayout.addWidget(self.tableView)
        mainLayout.addLayout(statusLayout)
        self.setLayout(mainLayout)

    # 设置表格
    def setTableView(self):

        # 声明查询模型
        self.queryModel = QSqlQueryModel(self)
        # 设置当前页
        self.currentPage = 1
        # 得到总记录数
        self.totalRecrodCount = self.getTotalRecordCount()
        # 得到总页数
        self.totalPage = self.getPageCount()
        # 刷新状态
        self.updateStatus()
        # 设置总页数文本
        self.setTotalPageLabel()
        # 设置总记录数
        self.setTotalRecordLabel()

        # 记录查询
        self.recordQuery(0)
        # 设置模型
        self.tableView.setModel(self.queryModel)

        # print('totalRecordCount = ' + str(self.totalRecrodCount))
        # print('totalPage=' + str(self.totalPage))

        # 设置表格头
        self.queryModel.setHeaderData(0, Qt.Horizontal, '编号')
        self.queryModel.setHeaderData(1, Qt.Horizontal, '姓名')
        self.queryModel.setHeaderData(2, Qt.Horizontal, '性别')
        self.queryModel.setHeaderData(3, Qt.Horizontal, '年龄')
        self.queryModel.setHeaderData(4, Qt.Horizontal, '院系')

    # 得到记录数
    def getTotalRecordCount(self):
        self.queryModel.setQuery("select * from student")
        rowCount = self.queryModel.rowCount()
        print('rowCount=' + str(rowCount))
        return rowCount

    # 得到页数
    def getPageCount(self):
        if self.totalRecrodCount % self.PageRecordCount == 0:
            return (self.totalRecrodCount / self.PageRecordCount)
        else:
            return (self.totalRecrodCount / self.PageRecordCount + 1)

    # 记录查询
    def recordQuery(self, limitIndex):
        szQuery = ("select * from student limit %d,%d" % (limitIndex, self.PageRecordCount))
        print('query sql=' + szQuery)
        self.queryModel.setQuery(szQuery)

    # 刷新状态
    def updateStatus(self):
        szCurrentText = ('当前第 %d 页' % self.currentPage)
        self.currentPageLabel.setText(szCurrentText)

        # 设置按钮是否可用
        if self.currentPage <= 1:
            self.prevButton.setEnabled(False)
        else:
            self.prevButton.setEnabled(True)

        if self.currentPage > self.totalPage - 1:
            self.nextButton.setEnabled(False)
        else:
            self.nextButton.setEnabled(True)

    # 设置总页数文本
    def setTotalPageLabel(self):
        szPageCountText = ('总共 %d 页' % self.totalPage)
        self.totalPageLabel.setText(szPageCountText)

    # 设置总记录数
    def setTotalRecordLabel(self):
        szTotalRecordText = ('共 %d 条' % self.totalRecrodCount)
        # print('*** setTotalRecordLabel szTotalRecordText=' + szTotalRecordText)
        self.totalRecordLabel.setText(szTotalRecordText)

    # 前一页被按下
    def onPrevButtonClick(self):
        print('*** onPrevButtonClick')
        limitIndex = (self.currentPage - 2) * self.PageRecordCount
        self.recordQuery(limitIndex)
        self.currentPage -= 1
        self.updateStatus()

    # 后一页被按下
    def onNextButtonClick(self):
        print('*** onNextButtonClick')
        limitIndex = self.currentPage * self.PageRecordCount
        self.recordQuery(limitIndex)
        self.currentPage += 1
        self.updateStatus()

    # 转到页按钮被按下
    def onSwitchPageButtonClick(self):
        # 得到输入的字符串
        szText = self.switchPageLineEdit.text()

        # 得到页数
        pageIndex = int(szText)
        # 判断是否有指定页
        if pageIndex > self.totalPage or pageIndex < 1:
            QMessageBox.information(self, '提示', "没有指定的页面,重新输入")
            return

        # 得到查询起始行号
        limitIndex = (pageIndex - 1) * self.PageRecordCount

        # 记录查询
        self.recordQuery(limitIndex)
        # 设置当前页
        self.currentPage = pageIndex
        # 刷新状态
        self.updateStatus()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = DataGrid()
    w.show()
    sys.exit(app.exec_())















